package com.ls.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import org.apache.commons.codec.binary.Hex;

public class MessageDigestTest {

    private static String TEST_DATA = "i am a test";

    public static void main(String[] args)
                    throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA");
        print(md);
        md = MessageDigest.getInstance("MD5");
        print(md);
        md = MessageDigest.getInstance("MD2");
        print(md);
        md = MessageDigest.getInstance("SHA-256");
        print(md);
        md = MessageDigest.getInstance("SHA-384");
        print(md);
        md = MessageDigest.getInstance("SHA-224");
        print(md);
        md = MessageDigest.getInstance("SHA-512");
        print(md);
    }

    private static void print(MessageDigest md) throws UnsupportedEncodingException {
        System.out.println("Algorithm:\t" + md.getAlgorithm());
        System.out.println("\tProvider:\t" + md.getProvider());
        long start = System.nanoTime();
        md.update(TEST_DATA.getBytes("UTF-8"));
        byte[] digest = md.digest();
        long time = System.nanoTime() - start;
        System.out.println("\tTime cost:\t" + time + "ns");
        System.out.println("\tByte length:\t" + digest.length);
        String digestBase64Str = Base64.getEncoder().encodeToString(digest);
        System.out.println("\tBase64:\t" + digestBase64Str + "\tlen:\t" + digestBase64Str.length());
        String digestHexStr = Hex.encodeHexString(digest);
        System.out.println("\tHex:\t" + digestHexStr + "\tlen:\t" + digestHexStr.length());
    }
}
